package cn.yunbamboos.rest.service.dto;

import cn.hutool.core.collection.CollectionUtil;
import cn.yunbamboos.Model;
import cn.yunbamboos.mybatis.metadata.IPage;
import cn.yunbamboos.rest.service.anno.param.ParamType;
import cn.yunbamboos.rest.service.anno.param.enums.Type;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.util.List;

public class Page<T extends Model> implements IPage<T>, Model {

    @ParamType(path = "current", type = Type.Integer, title = "当前页码", required = true, example = "1")
    private final int current;
    @ParamType(path = "size", type = Type.Integer, title = "每页条数", required = true, example = "10")
    private final int size;
    @ParamType(path = "rows", type = Type.Array, title = "行信息", required = true, typeClass = Model.class)
    private List<T> rows;
    @ParamType(path = "total_num", type = Type.Integer, title = "总数", required = true, example = "0")
    private int totalNum;
    private final int offset;

    public Page() {
        this(1);
    }

    public Page(int current) {
        this(current, 20);
    }

    public Page(int current, int size){
        this.current = current;
        this.size = size;
        this.offset = (current - 1) * size;
    }

    @Override
    public JSONObject encode() {
        JSONObject json = new JSONObject();
        json.put("current", this.current);
        json.put("size", this.size);
        JSONArray array = new JSONArray();
        if (CollectionUtil.isNotEmpty(this.rows)) {
            this.rows.forEach((model) -> {
                array.add(model.encode());
            });
        }
        json.put("rows", array);
        json.put("total_num", this.totalNum);
        return json;
    }

    @Override
    public List<T> getRows() {
        return rows;
    }

    @Override
    public IPage<T> setRows(List<T> rows) {
        this.rows = rows;
        return this;
    }

    @Override
    public int getTotal() {
        return totalNum;
    }

    @Override
    public IPage<T> setTotal(int totalNum) {
        this.totalNum = totalNum;
        return this;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public int getCurrent() {
        return current;
    }

    @Override
    public int getOffset() {
        return offset;
    }
}
